import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-22
 * Time: 16:14
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //建立连接
            //阻塞在客户端A等待输入请求，无法执行到这里和客户端B建立连接
            Socket socket = serverSocket.accept();
            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.submit(()->{
                //处理连接后的操作
                try {
                    processConection(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

        }
    }

    private void processConection(Socket socket) throws IOException {
        System.out.printf("[%s:%d]客户端上线\n", socket.getInetAddress(), socket.getPort());

           try(InputStream inputStream = socket.getInputStream();
               OutputStream outputStream = socket.getOutputStream();
               Scanner scanner = new Scanner(inputStream); //格式化读取
               PrintWriter writer = new PrintWriter(outputStream);){//格式化输入
                while(true){    //一次连接可能有多个请求，采用死循环结构
                    if(!scanner.hasNext()){ //客户端没发送请求并且每断开连接的时候，会阻塞在这里
                        System.out.printf("[%s:%d]客户端下线\n", socket.getInetAddress(), socket.getPort());
                        break;
                    }
                    //1.读取并解析请求
                    String request = scanner.next();
                    //2.根据读取的内容，计算出响应
                    String response = process(request);
                    //3.发送字节流数据
                    writer.println(response);
                    writer.flush();//刷新缓冲区，才能送到网卡
                    System.out.printf("[%s:%d] req: %s, resp: %s\n", socket.getInetAddress(), socket.getPort(),
                            request, response);
                }
           }finally {
               socket.close();//没有请求后，关闭客户端连接
           }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
